import React, { Component } from "react";
import { Form, Icon, Input, Button, Alert, Layout, Avatar, Modal, message, Select, Radio } from "antd";
import { getAccessTokenForOpenId, bindWeChatForOpenId, getUserInfoByWeChatIdForSendMsg, getUserWechatInfo, deleteWechatIdForSendMsg } from "../js/wechatapi.js";
import { iconFontUrl } from "../js/config.js";

const IconFont = Icon.createFromIconfontCN({
    scriptUrl: iconFontUrl
});

const FormItem = Form.Item;
const { Content } = Layout;

class LoginForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            visiable: false,
            msg: '',
            openid: this.props.location.state.openid
        };
    }

    handleSubmit(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                var usertype = {
                    "normal": 1,
                    "teacher": 2
                }
                console.log(usertype[values.userType])
                bindWeChatForOpenId(usertype[values.userType], values.userName, values.password, this.state.openid)
                    .then((res) => {
                        if (res.data.res == "success") {
                            this.props.history.push('/success')
                        } else {
                            this.setState({
                                visible: true,
                                msg: res.data.msg
                            });
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            }
        });
    }

    handleClose() {
        this.setState({ visible: false });
    }

    handleChange(value) {
        console.log(value)
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <div className="wechat-bind">
                <Form onSubmit={this.handleSubmit.bind(this)} className="wechat-bind-form">
                    <h1 style={{ textAlign: "center" }}>梯度智慧安监</h1>
                    <FormItem>
                        {getFieldDecorator("userType", {
                            initialValue: "normal",
                            rules: [{ required: true, message: "请选择账号类型!" }]
                        })(
                            <Radio.Group
                                style={{
                                    justifyContent: "center",
                                    display: "flex"
                                }}
                                size="large"
                                onChange = {(value)=>this.handleChange(value)}>
                                <Radio value="normal">一般用户</Radio>
                                <Radio value="teacher">签到用户</Radio>
                            </Radio.Group>
                            // <Select
                            //     defaultValue="normal"
                            //     size="large"
                            //     onChange={(value)=>this.handleChange(value)}
                            //     placeholder="类型"
                            // >
                            //     <Option value="normal">一般用户</Option>
                            //     <Option value="teacher">教师</Option>
                            // </Select>
                        )}
                    </FormItem>
                    <FormItem>
                        {getFieldDecorator("userName", {
                            rules: [{ required: true, message: "请输入帐号!" }]
                        })(
                            <Input
                                size="large"
                                prefix={
                                    <Icon type="user" style={{ color: "rgba(0,0,0,.25)" }} />
                                }
                                placeholder="帐号"
                            />
                        )}
                    </FormItem>
                    <FormItem>
                        {getFieldDecorator("password", {
                            rules: [{ required: true, message: "请输入密码!" }]
                        })(
                            <Input
                                size="large"
                                prefix={
                                    <Icon type="lock" style={{ color: "rgba(0,0,0,.25)" }} />
                                }
                                type="password"
                                placeholder="密码"
                            />
                        )}
                    </FormItem>
                    {
                        this.state.visible ?
                            (
                                <FormItem>
                                    <Alert message={this.state.msg} type="error" closable afterClose={this.handleClose.bind(this)} />
                                </FormItem>
                            ) : null
                    }
                    <FormItem>
                        <Button
                            type="primary"
                            htmlType="submit"
                            className="login-form-button"
                        >
                            绑定
                        </Button>
                    </FormItem>
                </Form>
            </div>
        );
    }
}

const wechatBind = Form.create()(LoginForm);

class success extends Component {
    handleClick() {
        window.WeixinJSBridge.call('closeWindow'); //微信浏览器提供的方法 关闭页面
    }

    render() {
        return (
            <Layout style={{
                backgroundColor: "#ffffff",
                textAlign: "center",
                height: "100%"
            }}>
                <Content style={{
                    paddingTop: "56px"
                }}>
                    <IconFont
                        type="icon-locationiconsuccess"
                        style={{
                            marginBottom: "30px",
                            fontSize: "93px"
                        }} />
                    <h2 style={{
                        marginBottom: "5px",
                        fontWeight: "400",
                        fontSize: "20px"
                    }}>操作成功</h2>
                    <p style={{
                        fontSize: "14px",
                        color: "#808080"
                    }}>您的微信账号与服务号已成功绑定，请直接关闭此页面</p>
                    <div style={{
                        margin: "1.17647059em 15px 0.3em"
                    }}>
                        <div onClick={this.handleClick}
                            style={{
                                color: "#ffffff",
                                backgroundColor: "#1AAD19",
                                position: "relative",
                                display: "block",
                                marginLeft: "auto",
                                marginRight: "auto",
                                paddingLeft: "14px",
                                paddingRight: "14px",
                                boxSizing: "border-box",
                                fontSize: "18px",
                                textAlign: "center",
                                textDecoration: "none",
                                lineHeight: "2.55555556",
                                borderRadius: "5px"
                            }}>
                            关闭此页面
                        </div>
                    </div>
                </Content>
            </Layout>
        );
    }
}

const confirm = Modal.confirm;
class userInfo extends Component {
    constructor(props) {
        super(props);
        this.state = {
            headimgurl: '',
            realname: '',
            openid: ''
        }
    }

    componentDidMount() {
        let code = this.getUrlParam("code")
        getAccessTokenForOpenId(code)
            .then((res) => {
                let openid = res.data.openid;
                let accessToken = res.data.access_token;
                this.setState({
                    openid: openid
                });
                getUserInfoByWeChatIdForSendMsg(openid)
                    // getUserInfoByWeChatIdForSendMsg("oK_0N079n3oSxMU4igzloJceguco")
                    .then((res) => {
                        // console.log(res);
                        if (res.data.isContain == true) { //该用户已绑定
                            this.setState({
                                realname: res.data.userInfo[0].realName,
                                identity: res.data.userInfo[0].identityString,
                                username: res.data.userInfo[0].username,
                                phone: res.data.userInfo[0].phone,
                                department: res.data.userInfo[0].departmentString
                            });
                            getUserWechatInfo(accessToken, openid)
                                .then((res) => {
                                    this.setState({
                                        headimgurl: res.data.headimgurl
                                        // headimgurl: 'http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLlQee7mLJFg2ryuczbhjgaBhI7fZAs9aIFBHicEUACKIP9xtMsibichGg8ianlBO7jf4grrRia0UWS4icg/132'
                                    });
                                })
                                .catch((e) => {
                                    if (e.response) {
                                        //请求已发出，服务器返回状态码不是2xx。
                                        console.info(e.response.data)
                                        console.info(e.response.status)
                                        console.info(e.response.headers)
                                    } else if (e.request) {
                                        // 请求已发出，但没有收到响应
                                        // e.request 在浏览器里是一个XMLHttpRequest实例，
                                        // 在node中是一个http.ClientRequest实例
                                        console.info(e.request)
                                    } else {
                                        //发送请求时异常，捕捉到错误
                                        console.info('error', e.message)
                                    }
                                    console.info(e.config)
                                });
                        } else {
                            this.props.history.push({ pathname: '/wechatBind', state: { openid: openid } });
                            // this.props.history.push({pathname: '/wechatBind', state: {openid: "oK_0N079n3oSxMU4igzloJceguco"}});
                        }
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            })
            .catch((e) => {
                if (e.response) {
                    //请求已发出，服务器返回状态码不是2xx。
                    console.info(e.response.data)
                    console.info(e.response.status)
                    console.info(e.response.headers)
                } else if (e.request) {
                    // 请求已发出，但没有收到响应
                    // e.request 在浏览器里是一个XMLHttpRequest实例，
                    // 在node中是一个http.ClientRequest实例
                    console.info(e.request)
                } else {
                    //发送请求时异常，捕捉到错误
                    console.info('error', e.message)
                }
                console.info(e.config)
            });
    }

    getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]);
        return null; //返回参数值
    }

    onClickListener = (that) => {
        confirm({
            title: '确定要解除绑定？',
            okText: '解除绑定',
            cancelText: '取消',
            centered: true,
            onOk() {
                deleteWechatIdForSendMsg(that.state.openid)
                    .then((res) => {
                        if (res.data == "success") {
                            that.props.history.push({ pathname: '/wechatBind', state: { openid: that.state.openid } });
                        } else {
                            message.error('解除绑定失败！');
                        }
                        this.setState({
                            visible: false,
                        });
                    })
                    .catch((e) => {
                        if (e.response) {
                            //请求已发出，服务器返回状态码不是2xx。
                            console.info(e.response.data)
                            console.info(e.response.status)
                            console.info(e.response.headers)
                        } else if (e.request) {
                            // 请求已发出，但没有收到响应
                            // e.request 在浏览器里是一个XMLHttpRequest实例，
                            // 在node中是一个http.ClientRequest实例
                            console.info(e.request)
                        } else {
                            //发送请求时异常，捕捉到错误
                            console.info('error', e.message)
                        }
                        console.info(e.config)
                    });
            },
            onCancel() {

            },
        });
    }

    render() {
        return (
            <Layout style={{
                height: '100%'
            }}>
                <Content style={{
                    position: 'relative',
                    height: '100%',
                    backgroundColor: '#fff',
                    padding: '24px',
                    margin: '24px'
                }}>
                    <div style={{
                        textAlign: 'center',
                        marginBottom: '24px'
                    }}>
                        <div style={{
                            marginTop: '40px',
                            marginBottom: '20px'
                        }}>
                            {
                                this.state.headimgurl == '' ?
                                    <Avatar size={110} icon="icon-touxiang-shi" /> :
                                    <Avatar size={110} src={this.state.headimgurl} />
                            }
                        </div>
                        <div style={{
                            fontSize: '20px',
                            lineHeight: '28px',
                            fontWeight: '500',
                            color: 'rgba(0, 0, 0, .85)',
                            marginBottom: '4px'
                        }}>
                            {this.state.realname}
                        </div>
                        <div>
                            {this.state.identity}
                        </div>
                    </div>
                    <div>
                        <p className='space-between' style={{
                            marginBottom: '8px',
                            paddingLeft: '26px',
                            position: 'relative'
                        }}>
                            <div>
                                <IconFont type="icon-xingmingyonghumingnicheng" style={{
                                    position: 'absolute',
                                    fontSize: '14px',
                                    left: '0',
                                    top: '4px'
                                }} />用户名
                            </div>
                            <div>
                                {this.state.username}
                            </div>
                        </p>
                        <p className='space-between' style={{
                            marginBottom: '8px',
                            paddingLeft: '26px',
                            position: 'relative'
                        }}>
                            <div>
                                <IconFont type="icon-dianhua" style={{
                                    position: 'absolute',
                                    fontSize: '14px',
                                    left: '0',
                                    top: '4px'
                                }} />联系方式
                            </div>
                            <div>
                                {this.state.phone}
                            </div>
                        </p>
                        <p className='space-between' style={{
                            marginBottom: '8px',
                            paddingLeft: '26px',
                            position: 'relative'
                        }}>
                            <div>
                                <IconFont type="icon-gongsi" style={{
                                    position: 'absolute',
                                    fontSize: '14px',
                                    left: '0',
                                    top: '4px'
                                }} />工作单位
                            </div>
                            <div>
                                {this.state.department}
                            </div>
                        </p>
                    </div>
                    <Button
                        style={{
                            position: 'absolute',
                            bottom: '0px',
                            left: '0px'
                        }}
                        type="primary"
                        className="login-form-button"
                        onClick={() => { this.onClickListener(this) }}>
                        解除绑定
                    </Button>
                </Content>
            </Layout>
        )
    }
}

export { wechatBind, success, userInfo };
